package cn.tedu.rms.type.service.impl;

import cn.tedu.rms.base.exception.ServiceException;
import cn.tedu.rms.base.response.StatusCode;
import cn.tedu.rms.dish.mapper.DishMapper;
import cn.tedu.rms.dish.pojo.dto.DishQuery;
import cn.tedu.rms.dish.pojo.vo.DishVo;
import cn.tedu.rms.type.mapper.TypeMapper;
import cn.tedu.rms.type.pojo.dto.TypeQuery;
import cn.tedu.rms.type.pojo.dto.TypeSaveParam;
import cn.tedu.rms.type.pojo.entity.Type;
import cn.tedu.rms.type.pojo.vo.TypeVO;
import cn.tedu.rms.type.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class TypeServiceImpl implements TypeService {
    @Autowired
    TypeMapper typeMapper;
    @Autowired
    DishMapper dishMapper;

    @Override
    public List<TypeVO> selectType(TypeQuery typeQuery) {
        log.debug("查询菜品分类业务,typeQuery:{}",typeQuery);
        List<TypeVO> list=typeMapper.selectType(typeQuery);
        return list;
    }

    @Override
    public void save(TypeSaveParam typeSaveParam) {
        log.debug("保存菜品分类业务,typeSaveParam:{}",typeSaveParam);
        Type type=new Type();
        BeanUtils.copyProperties(typeSaveParam,type);
        // 判断是否是新增还是修改
        if (type.getId()==null){
            log.debug("新增菜品分类业务");
            type.setCreateTime(new Date());
            typeMapper.insert(type);
        }else {
            log.debug("修改菜品分类业务");
            type.setUpdateTime(new Date());
            typeMapper.update(type);
        }
    }

    @Override
    public void deleteType(Long id) {
        log.debug("删除菜品分类业务,id:{}",id);
        // 判断如果该菜系下有菜品，则不能删除
        DishQuery dishQuery=new DishQuery();
        dishQuery.setTypeId(id);
        List<DishVo> list=dishMapper.selectDish(dishQuery);
        if (list.size()>0){
            throw new ServiceException(StatusCode.DISH_TYPE_NOT_EMPTY);
        }
        typeMapper.deleteTypeById(id);
    }

}
